import { createApp } from 'vue';
import { createPinia } from 'pinia';
import ElementPlus from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import App from './App.vue';
import router from './router';
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import 'virtual:svg-icons-register';
import '@/styles/index.scss';
import 'nprogress/nprogress.css';
import NProgress from 'nprogress'
import globalComponentRegister from '@/components/index';
import 'element-plus/dist/index.css';
import { getToken } from './utils/tokenUtil';
const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount('#app');
app.use(ElementPlus, {
	locale: zhCn,
});
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
	app.component(key, component);
}
app.use(globalComponentRegister);
// 配置全局路由守卫，进行路由鉴权
router.beforeEach((to, from, next) => {
	let token = getToken();
	// 1. 已经登陆的用户，不能进入登陆路由
	if ('/login' === to.fullPath) {
		if (token) {
			ElMessage.error({ message: '请先退出登录' });
			next('/');
		} else {
			NProgress.start(); // 开始进度条
			next();
		}
	} else {
		// 2. 请求非登陆界面，如果没登陆，需要先登陆
		if (token) {
			NProgress.start(); // 开始进度条
			next();
		} else {
			ElMessage.error({ message: '请先登录' });
			next('/login');
		}
	}
});
router.afterEach((to, from) => {
	NProgress.done(); // 结束进度条
});
